package com.blockchain.securewallet.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.ColorInt;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.text.style.UnderlineSpan;
import android.util.DisplayMetrics;
import android.view.TouchDelegate;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.blockchain.securewallet.R;
import com.blockchain.securewallet.WalletApp;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author 大灯泡
 * UI工具类
 */
public class UIHelper {

    public static final int ORIGINAL_VALUE = -100;

    // =============================================================tools
    // methods

    /**
     * dip转px
     */
    public static int dipToPx(float dip) {
        return (int) (dip * WalletApp.getInstance().getResources()
                .getDisplayMetrics().density + 0.5f);
    }

    /**
     * px转dip
     */
    public static int pxToDip(float pxValue) {
        final float scale = WalletApp.getInstance().getResources()
                .getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 将sp值转换为px值
     */
    public static int sp2px(float spValue) {
        final float fontScale = WalletApp.getInstance().getResources()
                .getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 获取屏幕宽高
     *
     * @param isWidth 是否用取宽度
     */
    public static int getWidthOrHeight(boolean isWidth) {
        DisplayMetrics metrics = new DisplayMetrics();
        ((WindowManager) WalletApp.getInstance()
                .getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay()
                .getMetrics(metrics);

        if (isWidth) {
            return metrics.widthPixels;
        } else {
            return metrics.heightPixels;
        }
    }


    /**
     * 获取屏幕分辨率：宽
     */
    public static int getScreenWidthPix(@Nullable Context context) {
        if (context == null) context = WalletApp.getInstance().getApplicationContext();
        int width = context.getResources().getDisplayMetrics().widthPixels;
        return width;
    }

    /**
     * 获取屏幕分辨率：高
     */
    public static int getScreenHeightPix(@Nullable Context context) {
        if (context == null) context = WalletApp.getInstance().getApplicationContext();
        int height = context.getResources().getDisplayMetrics().heightPixels;
        return height;
    }

    /**
     * 获取状态栏的高度
     */
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources()
                .getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources()
                    .getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 隐藏软键盘
     */
    public static void hideInputMethod(View view) {
        try {
            InputMethodManager imm = (InputMethodManager) view.getContext()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) {
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void hideInputMethod(final View view, long delayMillis) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                hideInputMethod(view);
            }
        }, delayMillis);
    }

    /**
     * 显示软键盘
     */
    public static void showInputMethod(View view) {
        if (view != null && view instanceof EditText) view.requestFocus();
        InputMethodManager imm = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
        }
    }

    /**
     * 显示软键盘
     */
    public static void showInputMethod(Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 多少时间后显示软键盘
     */
    public static void showInputMethod(final View view, long delayMillis) {
        if (view != null)
        // 显示输入法
        {
            view.postDelayed(new Runnable() {

                @Override
                public void run() {
                    UIHelper.showInputMethod(view);
                }
            }, delayMillis);
        }
    }

    /**
     * 扩大View的触摸和点击响应范围,最大不超过其父View范围（ABSListView无效）
     * 延迟300毫秒执行，使该方法可以在onCreate里面使用
     */
    public static void expandViewTouchDelegate(final View view, final int top, final int bottom, final int left, final int right) {
        if (view == null) {
            return;
        }
        if (view.getParent() != null) {

            ((View) view.getParent()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    Rect bounds = new Rect();
                    view.setEnabled(true);
                    view.getHitRect(bounds);

                    bounds.top -= top;
                    bounds.bottom += bottom;
                    bounds.left -= left;
                    bounds.right += right;

                    TouchDelegate touchDelegate = new TouchDelegate(bounds, view);

                    if (View.class.isInstance(view.getParent())) {
                        ((View) view.getParent()).setTouchDelegate(touchDelegate);
                        //Logger.ds("设置TouchDelegate");
                    }
                }
            }, 300);
        }
    }

    /**
     * 还原View的触摸和点击响应范围,最小不小于View自身范围
     */
    public static void restoreViewTouchDelegate(final View view) {
        if (view == null) {
            return;
        }

        if (view.getParent() != null) {

            ((View) view.getParent()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    Rect bounds = new Rect();
                    bounds.setEmpty();
                    TouchDelegate touchDelegate = new TouchDelegate(bounds, view);

                    if (View.class.isInstance(view.getParent())) {
                        ((View) view.getParent()).setTouchDelegate(touchDelegate);
                    }
                }
            }, 300);
        }
    }

    /**
     * 判断程序是否在前台
     */
    public static boolean isTopActivity(Context c) {
        String packageName = "com.chaincloud.securewallet";
        ActivityManager activityManager = (ActivityManager) c.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1);
        if (tasksInfo.size() > 0) {
            // 应用程序位于堆栈的顶层
            if (packageName.equals(tasksInfo.get(0).topActivity.getPackageName())) {
                return true;
            }
        }
        return false;
    }

    public static int[] getTextviewWidthAndHeight(TextView textView) {
        textView.setText("test");
        textView.measure(0, 0);
        int[] widthAndHeight = new int[]{textView.getMeasuredWidth(), textView.getMeasuredHeight()};
        textView.setText("");
        return widthAndHeight;
    }

    public static void safeOpenOrDismissDialog(@Nullable Dialog dialog, boolean isOpen) {
        if (dialog == null) {
            return;
        }
        if (isOpen) {
            if (!dialog.isShowing()) {
                dialog.show();
            }
        } else {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
        }
    }

    /**
     * 设置view的宽高，如果不需要设置，则传入UIHelper.ORIGINAL_VALUE
     */
    public static void setViewSize(View view, int width, int height) {
        if (view == null) {
            return;
        }
        if (view.getLayoutParams() == null) {
            return;
        }
        try {
            ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
            if (width != ORIGINAL_VALUE) {
                layoutParams.width = width;
            }
            if (height != ORIGINAL_VALUE) {
                layoutParams.height = height;
            }
            view.setLayoutParams(layoutParams);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void setViewsClickListener(@NonNull View.OnClickListener listener, View... views) {
        for (View view : views) {
            if (view != null) {
                view.setOnClickListener(listener);
            }
        }
    }


    public static void startChangeImageResourceWithFadeAinma(@NonNull final ImageView imageView, final int newImageResource) {
        final Animation anim_out = AnimationUtils.loadAnimation(imageView.getContext(), android.R.anim.fade_out);
        final Animation anim_in = AnimationUtils.loadAnimation(imageView.getContext(), android.R.anim.fade_in);
        anim_out.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                imageView.setImageResource(newImageResource);
                anim_in.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                    }
                });
                imageView.startAnimation(anim_in);
            }
        });
        imageView.startAnimation(anim_out);
    }

    //--(开始某个动画)
    public static void startAnimaListOverAndroid5(final ImageView v) {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
            if (v == null) return;
            v.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                @Override
                public boolean onPreDraw() {
                    try {
                        AnimationDrawable animationDrawable = (AnimationDrawable) v.getDrawable();
                        if (animationDrawable != null) animationDrawable.start();
                    } catch (Exception e) {

                    }
                    v.getViewTreeObserver().removeOnPreDrawListener(this);
                    return true;
                }
            });
        }
    }

    /**
     * =============================================================
     * 资源工具
     */

    public static int getResourceColor(int colorResId) {
        try {
            return WalletApp.getInstance().getResources().getColor(colorResId);
        } catch (Exception e) {
            return 0xff2296f3;
        }
    }

    public static void setViewVisibility(int visibility, View... views) {
        for (View view : views) {
            if (view.getVisibility() != visibility) {
                view.setVisibility(visibility);
            }
        }
    }


    public static void initHighLight(Activity activity, String content, String keyword, TextView tv, int color, boolean isNeedUnderLine) {
        SpannableString spanContent = new SpannableString(content);

        //关键词开始的标记
        int startIndex = content.indexOf(keyword);
        //关键词结束的索引标记
        int endIndex = content.indexOf(keyword) + keyword.length();

        ForegroundColorSpan colorSpan = new ForegroundColorSpan(activity.getResources().getColor(color));

        RelativeSizeSpan relativeSizeSpan = new RelativeSizeSpan(1.00f);
        //ClickSpan dicClickSpan = new ClickSpan(keyword);
        //StyleSpan styleSpan = new StyleSpan(Typeface.BOLD);

        if (startIndex < 0) {
            startIndex = 0;
        }
        if (endIndex < 0) {
            endIndex = 0;
        }
        
        if (isNeedUnderLine) {
            UnderlineSpan underlineSpan = new UnderlineSpan();
            spanContent.setSpan(underlineSpan, startIndex, endIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        }

        //SPAN_INCLUSIVE_INCLUSIVE 表示 前包 & 后包
        spanContent.setSpan(colorSpan, startIndex, endIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        spanContent.setSpan(relativeSizeSpan, startIndex, endIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

        //spanContent.setSpan(dicClickSpan, startIndex, endIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        //spanContent.setSpan(styleSpan, startIndex, endIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

        //设置文本过长时，内容可滑动
        //tv.setMovementMethod(LinkMovementMethod.getInstance());
        //设置用于显示选择高亮显示的颜色
        //tv.setHighlightColor(context.getResources().getColor(R.color.normal_text));

        tv.setText(spanContent);
    }

    //可以为Text设置点击事件
//    private class ClickSpan extends ClickableSpan {
//        private String words;
//
//        public ClickSpan(String words) {
//            this.words = words;
//        }
//
//        @Override
//        public void onClick(View widget) {
//            Logger.ds("点击了词条: " + words);
//        }
//    }


}
